package com.chapter_5;

import java.util.Random;

/**
 * @Author: Timo
 * @Date: 2019/5/15 14:44
 * @Description: 蛋糕师，制作蛋糕得师傅，每次制作完蛋糕之后就会放在桌子上，供给客人食用。
 * 因为桌子得大小是固定得，所有每张桌子所能放置得蛋糕数量是有限得，当桌子上得蛋糕摆满了之后，蛋糕师就不能继续往上摆蛋糕了，必须等
 * 桌子有空闲得地方出来之后才能继续往上摆蛋糕。
 */
public class MakerThread extends Thread {

    private final Table table;
    private final Random random;
    private static int id = 0;

    public MakerThread(String name, Table table, long seen) {
        super(name);
        this.random = new Random(seen);
        this.table = table;
    }

    /**
     * 业务执行得方法
     */
    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(random.nextInt(1_000));
                String cake = "[ Cake No."+nextId()+ " by "+getName()+"]";
                table.put(cake);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static synchronized int nextId() {
        return id++;
    }
}
